<template>
    <div class="workorder">
        <div class="page-head">
            <span class="head-text">当前工单:{{ leftForm.workOrderNumber }}</span>
            <span class="head-text">当前用户：{{ rightForm.operater }}</span>
        </div>
        <div class="page-main">
            <div class="main-left">
                <el-form :model="leftForm" :rules="leftFormRules" ref="leftForm" label-width="100px" label-position="left" size="mini" hide-required-asterisk class="demo-ruleForm">
                    <el-form-item label="订单编号" prop="orderCode" class="form-item">
                        <el-input v-model="leftForm.orderCode" placeholder="扫码读取订单编号" :disabled="true"></el-input>
                        <icon-svg name="sweep" width="2vw" height="2vw" color="" style="cursor:pointer;margin-left:1vw;" @click.native="sweep_btn('orderNum')"></icon-svg>
                    </el-form-item>
                    <el-form-item label="产品" prop="productionName">
                        <el-input v-model="leftForm.productionName" placeholder="自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="设备" prop="equipment_select">
                        <el-select v-model="leftForm.equipment_select" placeholder="请选择设备">
                            <el-option v-for="item in leftForm.equipmentOptions" :label="item.deviceName" :value="item.deviceId" :key="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="合格数" prop="qualifiedNum">
                        <el-input v-model.number="leftForm.qualifiedNum" @input="leftForm.qualifiedNum = String(leftForm.qualifiedNum).replace(/[^\d]/g, '')" placeholder="请输入合格数量"></el-input>
                    </el-form-item>
                    <el-form-item label="出勤工时" prop="attendanceHours">
                        <el-time-picker is-range v-model="leftForm.attendanceHours" format="HH:mm:ss" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围"></el-time-picker>
                    </el-form-item>
                    <el-form-item label="物料号" prop="meterialCode" class="form-item">
                        <el-input  placeholder="扫码读取物料号" v-model="leftForm.meterialCode" disabled></el-input>
                        <icon-svg name="sweep" width="2vw" height="2vw" color="" style="cursor:pointer;margin-left:1vw;" @click.native="sweep_btn('meterialCode')"></icon-svg>
                    </el-form-item>
                    <el-form-item label="物料名称" prop="meterialName">
                        <el-input  placeholder="物料名称自动读取" v-model="leftForm.meterialName" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="规格" prop="speicifation">
                        <el-input  placeholder="规格自动读取" v-model="leftForm.speicifation" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="单位" prop="organzation">
                        <el-input  placeholder="单位自动读取" v-model="leftForm.organzation" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="批次号" prop="batchCode_select">
                        <el-select v-model="leftForm.batchCode_select" placeholder="选择批次号">
                            <el-option v-for="item in leftForm.batchCodes" :label="item.label" :value="item.value" :key="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
            <div class="main-right">
                <el-form :model="rightForm" ref="rightForm" :rules="rightFormRules" label-width="100px" label-position="left" size="mini" hide-required-asterisk class="demo-ruleForm">
                    <el-form-item label="线体" prop="lineId">
                        <el-select v-model="rightForm.lineId" placeholder="请选择线体">
                            <el-option v-for="item in rightForm.lineCodeOptions" :label="item.name" :value="item.id" :key="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="时间" prop="time">
                        <el-time-picker v-model="rightForm.time" format="HH:mm:ss" :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="请选择时间"></el-time-picker>
                    </el-form-item>
                    <el-form-item label="操作员" prop="">
                        <el-input v-model="rightForm.operater" placeholder="操作员自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="完成数量" prop="finishedNum">
                        <el-input v-model.number="rightForm.finishedNum" @input="rightForm.unqualifiedNum = String(rightForm.finishedNum).replace(/[^\d]/g, '')" placeholder="请输入完成数量"></el-input>
                    </el-form-item>
                    <el-form-item label="不合格数" prop="unqualifiedNum">
                        <!-- <el-input v-model="rightForm.unqualifiedNum" disabled placeholder="自动计算合格数量"></el-input> -->
                        <el-input :value="badNum" disabled placeholder="自动计算合格数量"></el-input>
                    </el-form-item>
                    <el-form-item label="产品缺陷" prop="productDefect">
                        <el-input v-model="rightForm.productDefect" placeholder="请输入产品缺陷"></el-input>
                    </el-form-item>
                    <el-form-item label="计划数量" prop="planNumber">
                        <el-input v-model="rightForm.planNumber" placeholder="数量自动读取" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="已绑定物料数" prop="bindMeterialNum">
                        <el-input v-model="rightForm.bindMeterialNum" placeholder="数量自动读取" :disabled="true"></el-input>
                    </el-form-item>
                </el-form>
            </div>
        </div>
        <div class="page-footer">
            <el-button type="primary" size="mini" class="footer-btn" @click="save_btn">保存</el-button>
            <el-button type="primary" size="mini" class="footer-btn" @click="cancel_btn">取消</el-button>
        </div>
    </div>
</template>
  
<script>
import { getUserInfoAPI, getDeviceAPI, reqProductOrder, reqMaterialsInfo, reqLineList, reqBatchCode, reqSaveData } from "@/api/workOrder.js";
import { qrCode } from "@/utils/jingzhi.js";
export default {
    name:"workorder",
    data() {
        var validate1 = (rule, value, callback) => {
            let finishedNum =  this.rightForm.finishedNum;
            if (value === '') {
                callback(new Error('请输入合格数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的数量非法'));
            } else if(finishedNum !== '' && value > finishedNum){
                callback(new Error('输入的数量非法'));
            } else {
                callback();
            }
        };
        var validate2 = (rule, value, callback) => {
            let qualifiedNum =  this.leftForm.qualifiedNum;
            if (value === '') {
                callback(new Error('请输入完成数量'));
            } else if (parseInt(value < 0)) {
                callback(new Error('输入的数量非法'));
            } else if(qualifiedNum !== '' && value < qualifiedNum){
                callback(new Error('输入的数量非法'));
            } else {
                callback();
            }
        };
        return {
            //页面左侧表单数据
            leftForm: {
                orderId:"",  //订单id
                workOrderNumber:"",  //工单号
                orderCode:'',  //订单编号 MO2409100001  MO2409070001  SCDD20240907002
                productionName:'',  //产品
                equipment_select:'',  //设备
                equipmentOptions:[],
                qualifiedNum:'',
                attendanceHours:[new Date(), new Date()],  //出勤工时 开始时间-结束时间
                meterialCode:'',  //01.09001    06.0-56.0084    1111
                meterialName:'',
                speicifation:'',  //规格
                organzation:'',
                batchCode_select:"",
                batchCodes:[],  //批次号集合
                orderMaterialCode:""  //产品编码
            },
            leftFormRules: {
                orderCode:[{required:true, message:"订单号不能为空"}],
                productionName:[{required:false, message:"产品不能为空"}],
                equipment_select:[{required:true, message:"请选择设备", trigger: 'change'}],
                qualifiedNum: [{ validator: validate1, trigger: 'blur' }],  //合格数
                attendanceHours: [
                    { required: true, message: '出勤工时不能为空', trigger: 'change'}
                ],
                meterialCode:[{required:true, message:"物料号不能为空"}],
                meterialName:[{required:false, message:"物料名称不能为空"}],
                speicifation:[{required:false, message:"规格不能为空"}],
                organzation:[{required:false, message:"单位不能为空"}],
                batchCode_select:[{required:false, message:"请选择批次号", trigger: 'change'}],
            },
            rightForm: {
                lineId:'',  //线体
                lineCodeOptions:[],
                time:'',
                operater:'',
                operaterId:"",  //操作员id
                finishedNum:"",  //完成数量
                unqualifiedNum:'0',
                productDefect:"",  //产品缺陷
                bindMeterialNum:'',  //绑定物料数
                planNumber:''
            },
            rightFormRules: {
                lineId:[{required:true, message:"请选择线体", trigger: 'change'}],
                time:[{required:true, message:"请选择时间", trigger: 'change'}],
                // operater:[{required:false, message:"操作员不能为空"}],
                finishedNum:[{ validator: validate2, trigger: 'blur' }],
                unqualifiedNum:[{required:false, message:"不合格数量不能为空"}],
                productDefect:[{required:false, message:"请输入产品缺陷",trigger:'change'}],
                planNumber:[{required:false, message:"计划数量不能为空"}],
                bindMeterialNum:[{required:false, message:"绑定物料数不能为空"}],
            },
        };
    },
    mounted(){
        //获取当前用户
        this.getUserInfo();
        this.getDeviceList();
        this.getLineList();
    },
    computed:{
        badNum(){
            let qualifiedNum = this.leftForm.qualifiedNum;
            let finishedNum = this.rightForm.finishedNum;
            if( qualifiedNum !== '' && finishedNum !== '' && qualifiedNum >= 0 && finishedNum >= qualifiedNum){
                return finishedNum - qualifiedNum;
            }
            return '';
        }
    },
    methods: {
        //获取当前用户信息
        async getUserInfo () {
            let res = await getUserInfoAPI ();
            if(res.data.code === 200) {
                this.rightForm.operater = res.data.data.nickname;
                this.rightForm.operaterId = res.data.data.id;
            }
        },
        //获取设备列表接口
        async getDeviceList () {
            let res = await getDeviceAPI ();
            if(res.data.code === 200){
                let list = res.data.data.content.map(item => {
                    return {deviceCode:item.deviceCode,deviceId:item.deviceId,deviceName:item.deviceName};
                })
                this.leftForm.equipmentOptions = list;
            }
        },
        //查询线体相关信息
        async getLineList () {
            let res = await reqLineList();
            if(res.data.code === 200){
                this.rightForm.lineCodeOptions = res.data.data.map(item => {
                    return {id:item.id,name:item.name};
                })
            }
            console.log('获取线体相关的信息',res);
        },
        //通过订单编号查询产品信息
        async getProductOrder () {
            if(this.leftForm.orderCode === "") return this.$message({type:"warning",message:"订单编号不能为空!"});
            let res = await reqProductOrder (this.leftForm.orderCode);
            if(res.data.code === 200){
                this.leftForm.productionName = res.data.data.productOrderMaterial.materialFields.name;
                this.rightForm.planNumber = res.data.data.productOrderMaterial.planQuantity;
                this.leftForm.orderMaterialCode = res.data.data.productOrderMaterial.materialFields.code;
                this.leftForm.orderId = res.data.data.productOrderId;  //订单id
                this.leftForm.workOrderNumber = res.data.data.workOrderEntities[0].workOrderNumber;
            }
            console.log('通过订单编号查询产品信息',res);
        },
        //通过物料号查询物料数据
        async getMaterialsInfo () {
            if(this.leftForm.meterialCode === "") return this.$message({type:"warning",message:"物料编号不能为空!"});
            let res = await reqMaterialsInfo (this.leftForm.meterialCode);
            if(res.data.code === 200){
                const { name, standard, unitOne } = res.data.data.materialFields;
                this.leftForm.meterialName = name;
                this.leftForm.speicifation = standard;
                this.leftForm.organzation = unitOne;
            }
            console.log('通过物料号查询物料信息',res);
        },
        //通过物料号查询批次信息
        async getBatchCodeList () {
            if(this.leftForm.meterialCode === "") return this.$message({type:"warning",message:"物料编号不能为空!"});
            let res = await reqBatchCode (this.leftForm.meterialCode);
            if(res.data.code === 200){
                
            }
            console.log('通过物料号查询批次信息',res);
        },
        //保存、取消按钮
        async save_btn(){
            //校验左右表单数据
            let validateResult = false;
            this.$refs.leftForm.validate((valid) => {
                if (valid) {
                    validateResult = true;
                } else {
                    validateResult = false;
                    return false;
                }
            });
            this.$refs.rightForm.validate((valid) => {
                if (valid) {
                    validateResult = true;
                } else {
                    validateResult = false;
                    return false;
                }
            });
            if(!validateResult) return ;
            //准备参数
            const { orderId,orderCode,productionName,equipment_select, qualifiedNum, attendanceHours, meterialCode, meterialName,speicifation,organzation, batchCode_select, orderMaterialName, orderMaterialCode, workOrderNumber } = this.leftForm;
            const { lineId, time, operater, operaterId, unqualifiedNum, productDefect, planNumber, finishedNum } = this.rightForm;
            let paramsObj = {
                productOrderId:orderId,  //订单id
                productOrderNumber:orderCode,  //订单编号
                workCenterId:lineId,  //线体id
                workCenterName:this.rightForm.lineCodeOptions.filter(item => item.id === lineId)[0].name,  //线体名称
                orderMaterialCode:orderMaterialCode,  //产品编码
                orderMaterialName:productionName,  //产品名称
                time:this.formatDate(time,1),  //时间
                deviceCode:this.leftForm.equipmentOptions.filter(item => item.deviceId == equipment_select)[0].deviceCode,  //设备编码
                deviceName:this.leftForm.equipmentOptions.filter(item => item.deviceId == equipment_select)[0].deviceName,  //设备名称
                operation:operater,  //操作员
                operationId:operaterId,  //操作员id
                goodQuantity:qualifiedNum,  //合格数量
                finishQuantity:finishedNum,  //完成数量
                badQuantity:finishedNum - qualifiedNum,  //不合格数量unqualifiedNum
                workTimeStart:this.formatDate(attendanceHours[0]),  //出勤工时开始
                workTimeEnd:this.formatDate(attendanceHours[1]),  //出勤工时结束
                materialBad:productDefect,  //产品缺陷
                materialCode:meterialCode,  //物料号
                materialName:meterialName,  //物料名称
                materialStandard:speicifation,  //规格
                materialComp:organzation,  //单位
                quantity:planNumber,  //数量
                bindMaterialQuantity:"",  //绑定物料数量
                batch:"",  //批次号
                workOrderNumber:workOrderNumber  //工单号
            }
            //console.log(paramsObj);
            let res = await reqSaveData (paramsObj);
            if(res.data.code === 200) {
                this.$message({type:"success",message:"保存成功!"});
                //置空表单
                this.cancel_btn();
            } else {
                this.$message({type:"error",message:"保存失败,请重试!"});
            }
            console.log("保存数据api",res);
        },
        cancel_btn(){
            //表单重置
            this.$refs.leftForm.resetFields();
            this.$refs.rightForm.resetFields();
            //console.log('取消');
            this.leftForm.orderId = "";
            this.leftForm.workOrderNumber = "";
            this.leftForm.orderCode = "";
            this.leftForm.productionName = "";
            this.leftForm.equipment_select = "";
            this.leftForm.qualifiedNum = "";
            this.leftForm.attendanceHours = [];
            this.leftForm.meterialCode = "";
            this.leftForm.meterialName = "";
            this.leftForm.speicifation = "";
            this.leftForm.organzation = "";
            this.leftForm.batchCode_select = "";
            this.leftForm.orderMaterialCode = "";
            this.rightForm.lineId = "";
            this.rightForm.time = "";
            this.rightForm.finishedNum = "";
            this.rightForm.unqualifiedNum = "";
            this.rightForm.productDefect = "";
            this.rightForm.bindMeterialNum = "";
            this.rightForm.planNumber = "";
        },
        //点击扫码
        async sweep_btn(type){
            console.log('点击扫码');
            try {
                let res = await qrCode();
                // let res = true;
                if(res){
                    switch (type) {
                        case "orderNum":
                            //扫订单编号636306
                            this.leftForm.orderCode = res;
                            this.getProductOrder();
                            break;
                        case "meterialCode":
                            //扫物料编码
                            this.leftForm.meterialCode = res;
                            this.getMaterialsInfo();
                            this.getBatchCodeList();
                            break;
                        default:
                            break;
                    }
                }
                console.log('调用精致提供的扫码api',res);
            } catch (error) {
                this.$message({type:"warning",message:error});
            }
        },
        //格式化时间
        formatDate(val,type){
            let date = new Date(val);
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let h = date.getHours();
            let m = date.getMinutes();
            let s = date.getSeconds();
            if(type !== undefined){
                return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
            }
            return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        },
        addZero(val){
            return val > 9 ? val : "0" + val;
        }
    },
}
</script>
  
<style lang="scss" scoped>
  .workorder{
    width: 100vw;
    height: 100vh;
    display: flex;
    flex-direction: column;
    user-select: none;
    .page-head{
        width: 100vw;
        height: 10vh;
        padding: 0 5vw;
        box-sizing: border-box;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #4095e5;
        color: white;
        font-size: 1.5vw;
    }
    .page-main{
        width: 100vw;
        height: 75vh;
        display: flex;
        .main-left{
            width: 50%;
            height: 100%;
            padding: 1vw 10vw 1vw 3vw;
            box-sizing: border-box;
        }
        .main-right{
            width: 50%;
            height: 100%;
            padding: 1vw 10vw 1vw 3vw;
            box-sizing: border-box;
        }
    }
    .page-footer{
        width: 100%;
        height: 15vh;
        display: flex;
        justify-content: space-evenly;
        align-items: center;
        .footer-btn{
            width: 100px;
        }
    }
  }
  ::v-deep .is-required .el-form-item__label::after {
    content: "*";
    color: #ff0000;
    margin-left: 4px;
  }
  ::v-deep .el-form-item__content{
    display: flex;
    align-items: center;
    width: 22.2vw;
  }
  ::v-deep .form-item {
    .el-form-item__content{
        width: 25vw;
    }
  }
</style>
  